<template>
  <v-page
    v-model="refreshing"
    background="#f5f6fa"
    header-background="white"
    :empty="state === 'finished' && !complaintList.length"
    empty-oss-src="empty-order.png"
    empty-text="暂无投诉"
    padding-top="24rpx"
    @refresh="refreshHandle"
    @tolower="getComplaintList"
  >
    <template #header>
      <v-navbar title="投诉反馈" native />
    </template>
    <template #default>
      <complaint-item
        v-for="item in complaintList"
        :key="item.id"
        :complaint="item"
        @click="navigateToDetails(item)"
      />
      <v-loadmore :state="state" @reload="getComplaintList" />
    </template>
  </v-page>
</template>

<script setup lang="ts">
import ComplaintItem from './modules/complaint-item.vue';

const pageIndex = ref(1);
const state = ref<'loading' | 'finished' | 'error'>();
const complaintList = ref<OrderComplaintProgressVO[]>([]);

const getComplaintList = async () => {
  if (state.value !== undefined && state.value !== 'error') return;
  state.value = 'loading';
  const response = await $api.getOrderComplaintServiceProgress({
    page_no: pageIndex.value,
    page_size: 10
  });
  switch (response.__error) {
    case undefined:
      complaintList.value.push(...(response.data?.list ?? []));
      pageIndex.value++;
      if (complaintList.value.length >= response.data?.total) {
        state.value = 'finished';
      } else {
        state.value = undefined;
      }
      break;
    default:
      state.value = 'error';
  }
};
const refreshing = ref(false);
const refreshHandle = async () => {
  pageIndex.value = 1;
  complaintList.value = [];
  state.value = undefined;
  refreshing.value = true;
  await getComplaintList();
  refreshing.value = false;
};

let needToRefresh = false;
const setNeedToRefresh = () => (needToRefresh = true);
onLoad(() => {
  getComplaintList();
  uni.$on('refresh-complaint-list', setNeedToRefresh);
});
onShow(() => {
  if (needToRefresh) {
    refreshHandle();
    needToRefresh = false;
  }
});
onUnload(() => {
  uni.$off('refresh-complaint-list', setNeedToRefresh);
});

const navigateToDetails = (item: OrderComplaintProgressVO) => {
  uni.navigateTo({ url: `/pages/complaint/complaint-details?id=${item.id}` });
};
</script>

<style lang="scss" scoped></style>
